/**************************************************************************************************
 * *
 * HUSONG PROPRIETARY INFORMATION                                          *
 * *
 * The information contained herein is proprietary to HUSONG                           *
 * and shall not be reproduced or disclosed in whole or in part                       *
 * or used for any design or manufacture                                     *
 * without direct written authorization from HUSONG.                               *
 * *
 * Copyright (c) 2015 by HUSONG.  All rights reserved.                               *
 **************************************************************************************************/

package com.husong.mapper;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.springframework.stereotype.Component;

import com.husong.entity.Address;
import com.husong.entity.Complain;
import com.husong.entity.Message;
import com.husong.entity.Order;
import com.husong.entity.OrderBroker;
import com.husong.entity.OrderPic;
import com.husong.entity.OrderProgress;
import com.husong.entity.Red;
import com.husong.entity.User;
import com.husong.entity.Zan;
import com.husong.mapper.provider.OrderProvider;
import com.husong.pojo.ActivityFundPoolBean;
import com.husong.pojo.ActivityFundPoolLogBean;
import com.husong.pojo.AdvertBean;
import com.husong.pojo.ConmentBean;
import com.husong.pojo.EvaluateBean;
import com.husong.pojo.OrderBean;
import com.husong.pojo.OrderBrokerBean;
import com.husong.pojo.OrderTypeBean;
import com.husong.pojo.TipBean;
import com.husong.pojo.ZanBean;

/**
 * create by MaxMin.
 * <p/>
 * email: tjljob@126.com
 * <p/>
 * date:  2015年11月12日 17:31.
 */
@Component
public interface OrderMapper {

    /**
     * 发布订单
     *
     * @param order
     *
     * @return
     */
	@Insert("insert into hs_order(id,`desc`,tip,user_id,order_type_id,lng,lat,typ"
			+ ",fee,address_id,to_address_id,voice_path,isdelete,cityname,discount"
			+ ",order_status_id,need_cancel,broker_id,get_address_id,send_address_id,advert_id,order_no,create_date) "
			+ " values(#{orderId},#{desc},#{tip},#{userId},#{orderTypeId}"
			+ ",#{lng},#{lat},#{type},#{fee},#{addressId},"
			+ "#{toAddressId},#{voicePath},#{isdelete},#{cityname}"
			+ ",#{discount},#{statusId},#{needCancel},#{brokerId},#{getAddressId},#{sendAddressId},#{advertId},#{orderNo},#{createDate})")
    int create(Order order);
	/**
	 * 保存图片
	 * @return
	 */
	@Insert("insert into hs_order_pic(pic_id,path,order_id,create_date,update_date)"
			+ " values(#{picId},#{path},#{orderId},#{createDate},#{updateDate})")
	int saveOrderPic(OrderPic pic);

    /**
     * 获取订单详情
     *
     * @param orderid
     *
     * @return
     */
	@Select("SELECT o.*,o.typ as type,(SELECT GROUP_CONCAT(op.path) FROM hs_order_pic op WHERE op.order_id=o.id ) picpath"
			+ ",a1.name as fromName,a1.text as fromAddress,a1.telephone as fromTelephone"
			+ ",a2.text as toAddress,a2.name as toName,a2.telephone as toTelephone"
			+ ",u.username as uName,u.header as uHeader,u.telephone as uTelephone"
			+ ",b.username as bName,b.header as bHeader,b.telephone as bTelephone"
			+ ",r.amount redAmount,r.red_type as redType,r.red_desc as redDesc"
			+ ",a.type as advert_type "
			+ " FROM hs_order o "
			+ " left join hs_address a1 on a1.id=o.address_id"
			+ " left join hs_address a2 on a2.id=o.to_address_id"
			+ " left join hs_user u on u.id=o.user_id "
			+ " left join hs_user b on b.id=o.broker_id "
			+ " left join hs_red r on r.order_id=o.id "
			+ " left join hs_advert a on a.id=o.advert_id "
			+ "  WHERE o.id=#{orderid}")
    OrderBean get(String orderid);
	
	@Select(value="SELECT count(1) FROM hs_evaluate e WHERE e.orderid=#{orderid} and e.userid=#{userid}")
	Integer getEvaluateCount(Map<String,Object> params);
	
    /**
     * 按类型查询所有
     *
     * @param
     *
     * @return
     */
    @Select(value = "SELECT o.*,o.typ as type"
    		+ ",a1.name as fromName,a1.text as fromAddress,a1.telephone as fromTelephone"
			+ ",a2.text as toAddress,a2.name as toName,a2.telephone as toTelephone"
    		+ " FROM hs_order o "
    		+ " left join hs_address a1 on a1.id=o.address_id"
			+ " left join hs_address a2 on a2.id=o.to_address_id"
    		+ " WHERE order_type_id=#{type} AND cityname=#{cityname} AND isdelete=0  AND create_date<=#{lastDate}  AND o.id!=#{lastorderid} order by create_date desc limit 10")
    List<OrderBean> findAll(Map<String, Object> params);

    /**
     * 查询待抢单列表
     *
     * @param params
     *
     * @return
     */
    @SelectProvider(method="findWaitOrders",type=OrderProvider.class)
    List<OrderBean> findWaitOrders(Map<String, Object> params);
    /**
     * 查询首页呼单列表
     *
     * @param params
     *
     * @return
     */
    @SelectProvider(method="findIndexOrders",type=OrderProvider.class)
    List<OrderBean> findIndexOrders(Map<String, Object> params);

    /**
     * 查询雇主的呼送中订单
     *
     * @param key userid
     *
     * @return
     */
    @SelectProvider(method="findTaskingOrdersByUserId",type=OrderProvider.class)
    List<OrderBean> findTaskingOrdersByUserId(Map<String, Object> params);

    /**
     * 查询雇主的历史订单
     *
     * @param key userid
     *
     * @return
     */
    @SelectProvider(method="findHistoryOrdersByUserId",type=OrderProvider.class)
    List<OrderBean> findHistoryOrdersByUserId(Map<String, Object> params);

    /**
     * 查询经纪人任务中订单
     *
     * @param key userid
     *
     * @return
     */
    @SelectProvider(method="findTaskingOrdesrByBroker",type=OrderProvider.class)
    List<OrderBean> findTaskingOrdesrByBroker(Map<String, Object> params);

    /**
     * 查询经纪人历史订单
     *
     * @param key userid
     *
     * @return
     */
    @SelectProvider(method="findHistorygOrdesrByBroker",type=OrderProvider.class)
    List<OrderBean> findHistorygOrdesrByBroker(Map<String, Object> params);

    /**
     * 取消订单
     *
     * @param orderId
     *
     * @return
     */
    @Update(value = "UPDATE hs_order SET isdelete=1 WHERE id=#{orderId}")
    int delete(String orderId);
    /**
     * 取消订单
     *
     * @param orderId
     *
     * @return
     */
    @Update(value = "UPDATE hs_order SET need_cancel=1 WHERE id=#{orderId}")
    int need_cancel(String orderId);
    
    /**
     * 查询经纪人最后一次抢单时间
     * @param brokerid
     * @return
     */
    @Select(value="SELECT create_date FROM hs_order_broker where user_id=#{brokerid} order by create_date desc")
    List<Timestamp> getGrabOrderTimeByBrokerId(String brokerid);
    
    /**
     * 修改订单状态
     *
     * @param params
     *
     * @return
     */
    @Update(value = "UPDATE hs_order SET order_status_id=#{status} WHERE id=#{orderid} and order_status_id=#{oriStatus}")
    int updateOrderStatus(Map<String,Object> params);
    
    /**
     * 修改订单状态
     *
     * @param params
     *
     * @return
     */
    @Update(value = "UPDATE hs_order SET order_status_id=#{status},broker_id=#{broker_id} WHERE id=#{orderid} and order_status_id=#{oriStatus}")
    int updateOrder(Map<String,Object> params);
    
    /**
     * 追加小费
     *
     * @param params
     *
     * @return
     */
    @Update(value = "UPDATE hs_order SET tip=tip+#{tip} WHERE id=#{orderid} ")
    int appendTip(Map<String,Object> params);
    /**
     * 修改代购金额
     * @param params
     * @return
     */
    @UpdateProvider(method="updateOrderFee",type=OrderProvider.class)
    int updateOrderFee(Map<String,Object> params);
    
    @Insert(value="INSERT INTO hs_order_broker(id,user_id,order_id,is_checked,lng,lat,create_date) "
    		+ " values(#{id},#{userId},#{orderId},#{isChecked},#{lng},#{lat},#{createDate})")
    int insertOrderBroker(Map<String,Object> params);
    
    @Select(value="select count(1) from hs_order_broker where order_id=#{order_id} and user_id=#{user_id}")
    Integer getOrderBrokerCount(Map<String,Object> params);
    
    @SelectProvider(method="chooseBrokerList",type=OrderProvider.class)
    List<OrderBroker> chooseBrokerList(Map<String,Object> params);
    
    @Select(value="select * from hs_order_broker where id=#{id}")
    OrderBrokerBean getOrderBrokerBean(String id);
    
    @Update(value="update hs_order_broker set is_checked=#{is_checked},update_date=now() where id=#{id}")
    int updateOrderBroker(Map<String,Object> params);
    
    @Insert(value="insert into hs_order_progress(id,order_status,orderid,content,user_msg,create_date)  "
    		+ " values(#{id},#{order_status},#{orderid},#{content},#{user_msg},#{create_date})")
    int addOrderProgress(OrderProgress progress);
    
    @Select(value="select count(1) from hs_order_progress p where p.orderid=#{orderid} and order_status=#{order_status}")
    Integer getProgeressCount(Map<String,Object> params);
    
    @Select(value="select * from hs_order_progress where orderid=#{orderid} order by create_date")
    public List<OrderProgress> getOrderProgressesByOrderId(String orderid);
    
    @Select(value="select id as tipid,tip from hs_tip")
    List<TipBean> getTips();
    
    @Select(value="select id as typeId,type_name from hs_order_type")
    List<OrderTypeBean> getOrderTypes();
    
    @Select(value="select id as tipid,tip from hs_tip where id=#{id}")
    TipBean getTipById(long id);
    
    @Insert(value="insert into hs_address(id,name,telephone,text,user_id,create_date) values(#{addressid},#{name},#{telephone},#{text},#{user_id},#{create_date})")
    int insertAddress(Address address);
    
    @Update(value="update hs_address set isdelete=1 where id=#{id}")
    int deleteAddress(String id);
    
    @Select(value="select * from hs_address where id=#{id}")
    Address getAddressById(String id);
    
    @Update(value="update hs_address set name=#{name},telephone=#{telephone}"
    		+ ",text=#{text},user_id=#{user_id},create_date=#{create_date},update_date=#{update_date} where id=#{addressid}")
    int updateAddress(Address address);
    
    @Select(value="select *,id as addressid from hs_address where user_id=#{user_id} and isdelete=0 order by create_date desc")
    List<Address> getAddressesByUserId(String user_id);
    
    @Select(value ="select * from hs_advert where status =1 and isdelete=0 and start_time <=now() and end_time>now() and (cityname=#{cityname} or cityname='全国') ")
    List<AdvertBean> getAdverts(String cityname);
    
    @Select(value ="select count(1) from hs_user where cityname=#{cityname} and isbroker=1")
    Integer getBrokerCounts(String cityname);
    
    @Select(value="select * from hs_red where id=#{redid} and red_status=1 and active_begin_time<=now() and active_end_time>now()")
    Red getRed(String redid);

    @Insert(value="insert into hs_red( id,user_id,red_desc,order_id,amount,red_status,red_type,create_date,active_begin_time,active_end_time,cityname) "
    		+ " values(#{id},#{user_id},#{red_desc},#{order_id},#{amount},#{red_status},#{red_type},#{create_date},#{active_begin_time},#{active_end_time},#{cityname})")
    int addRed(Red red);
    
    @Select(value="select * from hs_red where user_id=#{userid} order by red_status asc,create_date desc")
    List<Red> getReds(String userid);
    
    @Select(value="select sum(r.amount) from hs_red r where r.user_id=#{user_id} and r.red_type=2")
    BigDecimal getInviteAmount(String user_id);
    
    @Select(value="select * from hs_red where user_id=#{userid} and red_status=1 and active_begin_time<=now() and active_end_time>now() order by red_status asc,create_date desc")
    List<Red> getUsefullReds(String userid);
    
    @Update(value="update hs_red set red_status=#{red_status},order_id=#{order_id} where id=#{id} ")
    int updateRed(Map<String,Object> params);
    
    @Select(value="select * from hs_activity_fund_pool where activity_type=#{activity_type} and city_name=#{city_name}")
    ActivityFundPoolBean getActivityFundPool(Map<String,Object> params);
    
    @Update(value="update hs_activity_fund_pool set amount=amount-#{amount} where id=#{id}")
    int updateActivityFundPool(Map<String,Object> params);
    
    @Insert(value="insert into hs_activity_fund_pool_log(id,activity_type,fund_id,activity_desc,amount,order_id,user_id,fund_code,create_time,city_name)"
    		+ " values(#{id},#{activity_type},#{fund_id},#{activity_desc},#{amount},#{order_id},#{user_id},#{fund_code},#{create_time},#{city_name})")
    int addActivityFundPoolLog(ActivityFundPoolLogBean log);
    
    @Insert(value="insert into hs_evaluate(id,point,content,orderid,userid,create_date) "
    		+ " values(#{id},#{point},#{content},#{orderid},#{userid},#{create_date})")
    int addEvaluate(EvaluateBean evaluate);
    
    @SelectProvider(method="getBrokerToMeEvalustes",type=OrderProvider.class)
    List<EvaluateBean> getBrokerToMeEvalustes(Map<String,Object> params);
    
    @SelectProvider(method="getUserToMeEvalustes",type=OrderProvider.class)
    List<EvaluateBean> getUserToMeEvalustes(Map<String,Object> params);
    
    @SelectProvider(method="getMeToBrokerEvalustes",type=OrderProvider.class)
    List<EvaluateBean> getMeToBrokerEvalustes(Map<String,Object> params);
    
    @SelectProvider(method="getMeToUserEvalustes",type=OrderProvider.class)
    List<EvaluateBean> getMeToUserEvalustes(Map<String,Object> params);
    
    @Insert(value="insert into hs_comment(id,content,user_id,order_id,parent_comment_id,create_date, update_date) "
    		+ " values(#{id},#{content},#{user_id},#{order_id},#{parent_comment_id},#{create_date}, #{update_date}) ")
    int addConment(ConmentBean conment);
    
    @Select(value="select * from hs_comment where id=#{parent_comment_id}")
    ConmentBean getConment(String parent_comment_id);
    
    @SelectProvider(method="getComments",type=OrderProvider.class)
    List<ConmentBean> getComments(Map<String, Object> params);
    
    @Insert(value="insert into hs_zan(user_id,order_id,status,create_date) "
    		+ " values(#{user_id},#{order_id},#{status},#{create_date})")
    int addZan(ZanBean zan);
    
    @Select(value="select * from hs_zan where user_id=#{user_id} and order_id=#{order_id}")
    ZanBean getZan(Map<String,Object> params);
    
    @Update(value="update hs_zan set status=#{status} where user_id=#{user_id} and order_id=#{order_id}")
    int updateZanStatus(Map<String,Object> params);
    
    @Select(value="select z.zid,u.header from hs_zan z left join hs_user u on u.id=z.user_id where z.order_id=#{order_id} and status=1")
    List<Zan> getZans(String order_id);
    
    @Select(value="select count(1) from hs_zan where order_id=#{order_id} and status=1")
    Integer getZanCount(String order_id);
    
    @Select(value="select count(1) from hs_comment where order_id=#{order_id}")
    Integer getConmentCount(String order_id);
    
    /**
	 * 添加消息记录
	 * 
	 * @param message
	 * @return
	 */
	@Insert(value = "INSERT INTO hs_message (message,user_id,user_type,type,orderid,from_user_id,createtime,updatetime) "
			+ "values (#{message},#{userId},#{userType},#{type},#{orderId},#{fromUserId},#{createtime},#{updatetime})")
	public int addMessage(Message message);
	
	/**
	 * 获取消息列表
	 * 
	 * @param params
	 * @return 
	 * @author maxmin
	 * @date 2015年8月31日下午4:54:37
	 */
	@SelectProvider(method="getMessages",type=OrderProvider.class)
	public List<Message> getMessages(Map<String, Object> params);
	
	@Select(value="select count(1) from hs_order o where o.order_status_id>7 and o.user_id=#{user_id}")
	Integer getFinishedOrderCount(String user_id);
	
	@Select(value="insert into hs_complain(text,order_id,telephone,createtime,updatetime,user_id) "
			+ " values(#{text},#{order_id},#{telephone},#{createtime},#{updatetime},#{user_id}) ")
	Integer complain(Complain complain);
	
	@Select(value="select * from hs_user where id in (select user_id from hs_order_broker where order_id =#{orderid})")
	List<User> getUsers(String orderid);
}
